#define DHTPIN 10 // 设置DHT11连接的引脚
#define DHTTYPE DHT11 // 设置使用的传感器类型

#include <ArduinoJson.h>
#include <DHT.h>
// 自定义模块
#include "MqttModule/MyMqtt.h"

DHT dht(DHTPIN, DHTTYPE); // 创建DHT对象

void send_discovery_messages() {
    String temperature_topic = "homeassistant/sensor/esp32/temperature/config";
    String humidity_topic = "homeassistant/sensor/esp32/humidity/config";

    String temperature_payload = R"(
    {
        "name": "ESP32 Temperature",
        "state_topic": "home/esp32/temperature",
        "unit_of_measurement": "°C",
        "device_class": "temperature",
        "unique_id": "esp32_temperature",
        "device": {
            "identifiers": ["esp32"],
            "name": "ESP32",
            "model": "ESP32",
            "manufacturer": "ESP"
        }
    }
    )";

    String humidity_payload = R"(
    {
        "name": "ESP32 Humidity",
        "state_topic": "home/esp32/humidity",
        "unit_of_measurement": "%",
        "device_class": "humidity",
        "unique_id": "esp32_humidity",
        "device": {
            "identifiers": ["esp32"],
            "name": "ESP32",
            "model": "ESP32",
            "manufacturer": "ESP"
        }
    }
    )";

    mqClient.publish(temperature_topic.c_str(), temperature_payload.c_str(), true);
    mqClient.publish(humidity_topic.c_str(), humidity_payload.c_str(), true);
}

String createHtMessage(float h,float t)
{
    StaticJsonDocument<200> doc;
    doc["type"] = "T&H";
    doc["device"] = macAddress;
    doc["temperature"] = t;
    doc["humidity"] = h;
    
    doc["temperatureUnit"] = "°C";
    doc["humidityUnit"] = "%";

    String jsonString;
    serializeJson(doc, jsonString);
    return jsonString;
}

void getTemperature()
{
  

  float h = dht.readHumidity();
  float t = dht.readTemperature();

  if (isnan(h) || isnan(t) ) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

  Serial.print(F("Humidity: "));
  Serial.print(h);
  Serial.print(F("%  Temperature: "));
  Serial.print(t);
  Serial.print(F("°C "));
  Serial.println();

    mqClient.publish("esp32/senser/", createHtMessage(h,t).c_str());

    // 发布温度数据到Home Assistant
    if (!isnan(t)) {
        mqClient.publish("home/esp32/temperature", String(t).c_str());
    }

    // 发布湿度数据到Home Assistant
    if (!isnan(h)) {
        mqClient.publish("home/esp32/humidity", String(h).c_str());
    }

    delay(5000);
}

